<template>
    <div class="default-main">
        <!-- <el-card shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="等级名称" prop="levelName">
                    <el-input
                        class="w-[280px]"
                        v-model="queryParams.levelName"
                        placeholder="请输入等级名称"
                        clearable
                        @keyup.enter="resetPage"
                    />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select
                        class="w-[280px]"
                        v-model="queryParams.status"
                        placeholder="请选择状态"
                        clearable
                    >
                        <el-option label="启用" :value="1" />
                        <el-option label="禁用" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card> -->
        <el-card shadow="never" class="!border-none mt-4">
            <!-- <div>
                <el-button type="primary" @click="handleAdd">
                    <template #icon>
                        <icon name="el-icon-Plus" />
                    </template>
                    新增等级
                </el-button>
            </div> -->
            <el-table class="mt-4" size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="等级名称" prop="title" min-width="120" />
                <el-table-column label="等级" prop="level" min-width="80" />
                <el-table-column label="优惠比例" prop="rate" min-width="100">
                    <template #default="{ row }">
                        {{ row.rate }}%
                    </template>
                </el-table-column>
                <el-table-column label="升级所需下单数" prop="order_num" min-width="140" />
                <el-table-column label="状态" prop="status" min-width="80">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="创建时间" prop="createTime" min-width="180" /> -->
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            link
                            @click="handleEdit(row)"
                        >
                            编辑
                        </el-button>
                        <!-- <el-button
                            type="danger"
                            link
                            @click="handleDelete(row.id)"
                        >
                            删除
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <!-- 新增/编辑弹窗 -->
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="500px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="formData"
                label-width="120px"
                :rules="formRules"
            >
                <el-form-item label="等级名称" prop="levelName">
                    <el-input
                        v-model="formData.title"
                        placeholder="请输入等级名称"
                        maxlength="50"
                        show-word-limit
                        :disabled="true"
                    />
                </el-form-item>
                <el-form-item label="等级" prop="level">
                    <el-input-number
                        v-model="formData.level"
                        :min="1"
                        :max="99"
                        placeholder="请输入等级"
                        class="w-full"
                        :disabled="true"
                    />
                </el-form-item>
                <el-form-item label="优惠比例" prop="rate">
                    <el-input-number
                        v-model="formData.rate"
                        :min="0"
                        :max="100"
                        :precision="2"
                        placeholder="请输入优惠比例"
                        class="w-full"
                    />
                    <div class="text-tx-secondary text-xs mt-1">单位：%，0-100之间的数值</div>
                </el-form-item>
                <el-form-item label="升级所需下单数" prop="order_num">
                    <el-input-number
                        v-model="formData.order_num"
                        :min="0"
                        placeholder="请输入升级所需下单数"
                        class="w-full"
                    />
                </el-form-item>
                <!-- <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item> -->
            </el-form>
        </popup>
    </div>
</template>

<script setup lang="ts" name="vipManage">
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { apiUserLevelList, apiUserLevelDetail, apiUserLevelSave } from '@/api/port'

// 查询参数
const queryParams = reactive({
    levelName: '',
    status: ''
})

// 表单数据
const formData = reactive({
    id: '',
    rate: 0,
    order_num: 0,
})

// 表单验证规则
const formRules = {
    levelName: [
        { required: true, message: '请输入等级名称', trigger: 'blur' }
    ],
    level: [
        { required: true, message: '请输入等级', trigger: 'blur' }
    ],
    discountRate: [
        { required: true, message: '请输入优惠比例', trigger: 'blur' }
    ],
    requiredOrders: [
        { required: true, message: '请输入升级所需下单数', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
}

// 弹窗相关
const popupRef = shallowRef<InstanceType<typeof popup>>()
const popupTitle = ref('')
const mode = ref('add')

// 分页相关
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: apiUserLevelList,
    params: queryParams
})

// 新增
const handleAdd = () => {
    mode.value = 'add'
    popupTitle.value = '新增VIP等级'
    resetFormData()
    popupRef.value?.open()
}

// 编辑
const handleEdit = async (row: any) => {
    mode.value = 'edit'
    popupTitle.value = '编辑VIP等级'
    try {
        // const data = await apiUserLevelDetail({ id: row.id })
        Object.assign(formData, row)
        popupRef.value?.open()
    } catch (error) {
        feedback.msgError('获取等级详情失败')
    }
}

// 删除
const handleDelete = async (id: number) => {
    await feedback.confirm('确定要删除该VIP等级吗？')
    try {
        await apiUserLevelSave({ id, is_delete: 1 })
        feedback.msgSuccess('删除成功')
        getLists()
    } catch (error) {
        feedback.msgError('删除失败')
    }
}

// 提交表单
const handleSubmit = async () => {
    try {
        // const submitData = { ...formData }
        const submitData = {
            id: formData.id,
            rate: formData.rate,
            order_num: formData.order_num,
        }
        // if (mode.value === 'add') {
        //     delete submitData.id
        // }
        await apiUserLevelSave(submitData)
        const action = mode.value === 'add' ? '新增' : '编辑'
        feedback.msgSuccess(`${action}成功`)
        popupRef.value?.close()
        getLists()
    } catch (error) {
        const action = mode.value === 'add' ? '新增' : '编辑'
        feedback.msgError(`${action}失败`)
    }
}

// 关闭弹窗
const handleClose = () => {
    resetFormData()
}

// 重置表单数据
const resetFormData = () => {
    Object.assign(formData, {
        id: '',
        levelName: '',
        level: 1,
        discountRate: 0,
        requiredOrders: 0,
        status: 1
    })
}

// 页面激活时获取列表
onActivated(() => {
    getLists()
})
</script>

<style scoped lang="scss"></style>